package com.tingyuge.thinking.spring.configuration.metadata;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.BeanMetadataAttributeAccessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.AttributeAccessor;
import org.springframework.util.ObjectUtils;

/**
 * bean 配置元信息
 * {@link BeanMetadataAttributeAccessor}
 * {@link AttributeAccessor}
 * @author xiaodao
 * @version 1.0
 * @date 2021/7/11
 */
public class BeanConfigurationMetadataDemo {
    public static void main(String[] args) {
        // beanDefinition的定义 (声明)
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder.addPropertyValue("name", "听雨阁");
        //获取AbstractBeanDefinition
        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        //附加属性(不影响bean  实例化 属性赋值 初始化)
        beanDefinition.setAttribute("name","小刀");
        //当前BeanDefinition 来自与哪里(也是赋值作用)
        beanDefinition.setSource(BeanConfigurationMetadataDemo.class);
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        beanFactory.registerBeanDefinition("user",beanDefinition);
        beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(bean.getClass())) {
                    BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
                    //BeanMetadataAttributeAccessor.source 来进行判断
                    if(BeanConfigurationMetadataDemo.class.equals(bd.getSource())){
                        //属性  (存储) 上下文
                        String name = (String) bd.getAttribute("name");
                        User user = (User)bean;
                        user.setName(name);

                    }



                }
                return bean;
            }
        });
        User user = beanFactory.getBean("user", User.class);
        System.out.println(user);

    }
}
